<template>
  <div class="app-container">

    <!-- 搜索表单 -->
    <el-form ref="queryRef" :inline="true" label-width="68px">
      <el-form-item label="名称" prop="name">
        <el-input
            v-model="condition.name"
            placeholder="请输入名称"
            clearable
        />
      </el-form-item>
      <el-form-item>
        <el-button
            v-hasPermi="['device:cabinetType:query']"
            :disabled="sineIe"
            type="primary"
            icon="Search"
            @click="getCabinetTypeList">搜索</el-button>
        <el-button icon="Refresh">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 功能按钮栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="addCabinetTypesml"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            @click="deletetype()"
        >删除</el-button>
      </el-col>
    </el-row>

    <!-- 数据展示表格 -->
    <el-table :data="cabinetTypeList" @selection-change="handleselectionchange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="名称" prop="name" width="150"/>
      <el-table-column label="总插槽数量" prop="totalSlots" width="110"/>
      <el-table-column label="描述" prop="description" />
      <el-table-column label="状态" prop="status" width="100">
        <template #default="scope">
          {{ scope.row.status == '1' ? '正常' : '停用' }}
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="{ row }">
          <el-button link type="primary" icon="Edit" @click="updateCabinetTypesml(row)">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="deletetypeD(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页条组件 -->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        v-model:current-page="condition.pageNum"
        :page-sizes="[10, 20, 30, 50]"
        v-model:page-size="condition.pageSize"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
    />
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="cabinetTypeRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="总插槽数量" prop="totalSlots">
          <el-select
              v-model="form.totalSlots"
              class="m-2"
              placeholder="请选择总插槽数量"
              style="width: 100%"
          >
            <el-option
                v-for="item in 20"
                :key="item"
                :label="item"
                :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="addUpdate">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>

import {listOfCabinetMachineTypes,addCabinetType,updateCabinetType,delCabinetType,deletedms} from '../../../api/device/type.js'
import {addCabinet, updateCabinet} from "@/api/device/cabinet.js";
import {getCurrentInstance} from "vue";
const { proxy } = getCurrentInstance()

//定义分页列表数据模型
const cabinetTypeList = ref([]);
const total = ref(0);
const sineIe = ref(false)
const open = ref(false)
const form = ref({})
const title = ref('')
const ids = ref([])

const data = reactive({
  condition:{
    name: '',
    pageNum: 1,
    pageSize: 10,
  },
  rules: {
    name: [
      { required: true, message: "名称不能为空", trigger: "blur" }
    ],
    totalSlots: [
      { required: true, message: "总插槽数量不能为空", trigger: "blur" }
    ],
  }
});
const {condition,rules} = toRefs(data)

/**
 * 单删
 */
async function deletetypeD(id) {
  let _ids = id;
  try {
    await proxy.$modal.confirm('是否确认删除充电宝柜机编号为"' + _ids + '"的数据项？');

    await deletedms(_ids); // 确保等待删除操作完成

    proxy.$modal.msgSuccess("删除成功");

    await getCabinetTypeList(); // 确保在删除完成后执行查询

  } catch (error) {
    // 用户取消或操作失败
    console.error("删除操作取消或失败:", error);
  }
}

/**
 * 批量删除
 * @param row
 * @constructor
 */
async function deletetype(){
  try {

    let _ids = ids.value;

    proxy.$modal.confirm('是否确认删除充电宝柜机编号为"' + _ids + '"的数据项？');

    await delCabinetType(_ids);

    proxy.$modal.msgSuccess("删除成功");

    await getCabinetTypeList();
  } catch (error) {
    // 用户取消或操作失败
    console.error("删除操作取消或失败:", error);
  }


}

/**
 * 多选数据
 */
function handleselectionchange(selection){
  ids.value = selection.map(item => item.id)
  console.log("多选框选中数据：",ids.value)
}
/**
 * 类型修改
 * @param val
 */
function updateCabinetTypesml(row){
  console.log("修改：",row)
  open.value = true
  title.value = 'update'
  form.value = JSON.parse(JSON.stringify(row));
}

/**
 * 类型添加
 * @param val
 */
function addCabinetTypesml(){
  open.value = true
  title.value = 'add'
  form.value = {}
}

/**
 * 类型提交
 * @param val
 */
function addUpdate(){
  const operation = title.value === 'add' ? addCabinetType : updateCabinetType
  let src = form.value
  operation(src).then(res => {
    if (res.code === 200) {
      proxy.$modal.msgSuccess(`${title.value === 'add' ? '新增' : '修改'}成功`)
      getCabinetTypeList();
      open.value = false
      localStorage.removeItem("layout-setting")
    } else {
      proxy.$modal.msgError(res.msg || "操作失败")
    }
  })

}

// 每页条数变化处理
const handleSizeChange = (val) => {
  condition.value.pageSize = val;
  getCabinetTypeList(); // 调用获取数据的方法
};

// 当前页码变化处理
const handleCurrentChange = (val) => {
  condition.value.pageNum = val;
  getCabinetTypeList(); // 调用获取数据的方法
};


/**
 * 柜机类型列表
 * */
const getCabinetTypeList = async () => {
  try {
    const res = await listOfCabinetMachineTypes(condition.value)

    // 根据后端返回结构调整
    cabinetTypeList.value = res.data?.list || res.data || []
    total.value = res.data?.total || res.total || 0

    console.log("当前页数据:", cabinetTypeList.value.length)
    console.log("总记录数:", total.value)
  } catch (error) {
    console.error("获取数据失败:", error)
  }
}


/**
 * 初始化加载
 */
onMounted(() => {
  getCabinetTypeList()
})
</script>